package cn.hls.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import cn.hls.dao.RoleDao;
import cn.hls.entity.Role;
import cn.hls.entity.vo.PageInfo;
import cn.hls.exception.BussinessException;
import cn.hlsconstant.DataAssessEnum;

@Component("roleDaoImpl")
public class RoleDaoImpl extends BaseDaoImpl<Role> implements RoleDao {

	@Override
	public PageInfo<Role> loadRoleInfo(Role entity, PageInfo<Role> page)
			throws Exception {
		// 定义查询hql语句
		StringBuilder selectHql = new StringBuilder();
		// 定义汇总hql语句
		StringBuilder countHql = new StringBuilder();
		// 定义查询条件参数
		List<Object> paramList = new ArrayList<Object>();
		selectHql.append("from Role r where deleted=? ");
		paramList.add(false);
		if (entity != null) {
			if (StringUtils.hasText(entity.getRoleName())) {
				selectHql.append("and roleName like ? ");
				paramList.add("%" + entity.getRoleName() + "%");
			}
			if (StringUtils.hasText(entity.getRoleCode())) {
				selectHql.append("and roleCode=? ");
				paramList.add(entity.getRoleCode());
			}
		}
		countHql.append("select count(id) ").append(selectHql);
		try {
			return find(selectHql.toString(), countHql.toString(),
					paramList.toArray(), page);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BussinessException(DataAssessEnum.SELECT_ERROR,"角色数据查询失败");
		}
	}

	public boolean checkRoleCode(String code) throws Exception {
		String hql = "select count(id) from Role where code=? and deleted=?";
		try {
			List<Role> list = findByHql(hql, new Object[] { code, false });
			if (list != null && list.size() > 0) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new BussinessException(DataAssessEnum.SELECT_ERROR,"代码为"+code+ "的角色信息查询失败");
		}
	}

}
